<template>
  <div class="order-container">
    <el-card v-if="data.length !== 0" class="box-card" v-for="(order, index) in data" :key="index">
      <div slot="header" class="clearfix">
        <span><strong>订单号：</strong>{{ order.order.orderSn }}</span>
        <span class="float-right"><strong>支付金额：</strong>¥{{ order.order.payAmount.toFixed(2) }}</span>
        <span style="color: red" v-if="order.timeout">剩余支付时间：{{ (order.timeout / 60).toFixed(0) }}分钟</span>
        <el-button v-if="order.order.status !== 3
        && order.order.status !== 5" type="primary" @click="handleOrderAction(order.order)">
          {{ btnStatus(order.order.status) }}
        </el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <p><strong>用户名：</strong>{{ order.order.memberUsername }}</p>
          <p style="color: #1ab394"><strong>订单状态：</strong>{{ getOrderStatus(order.order.status) }}</p>
        </el-col>
        <el-col :span="12">
          <p><strong>收货人：</strong>{{ order.order.receiverName }}</p>
          <p><strong>收货地址：</strong>{{ setAddress(order.order) }}</p>
        </el-col>
      </el-row>

      <el-divider></el-divider>

      <h3>订单商品列表</h3>
      <el-table :data="order.orderItemList" style="width: 100%">
        <el-table-column label="商品图片" width="100">
          <template slot-scope="scope">
            <el-image :src="scope.row.productPic" :preview-src-list="[scope.row.productPic]"
                      style="width: 80px; height: 80px"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
        <el-table-column prop="productBrand" label="品牌"></el-table-column>
        <el-table-column label="价格">
          <template slot-scope="scope">
            ¥{{ scope.row.productPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="productQuantity" label="数量"></el-table-column>
        <el-table-column label="规格">
          <template slot-scope="scope">
            {{ getProductAttr(scope.row.productAttr) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{row, $index}">
            <el-button type="text" v-if="order.order.status === 2 || order.order.status === 5" @click="handleOrderReturn(order.order, row)">申请售后
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div v-if="data.length === 0">
      <el-empty
          image="https://shyvv-1308916267.cos.ap-chengdu.myqcloud.com/mall/58881654671202045.png"
          :image-size="500"
          description="我们开始购物吧!"/>
    </div>

    <el-dialog
        title="退货详细"
        :visible.sync="showReturn"
        width="50%"
        @close="resetForm"
    >
      <div v-if="reasonForm.status==4" style="text-align: left">
        <el-row>
          拒绝原因:
          <el-input v-model="reasonForm.handleNote"
 type="textarea" disabled placeholder="请填写拒绝原因"></el-input>
        </el-row>
        <el-row style="color: red">
       注意： 如不满意该结果，请联系客服进行沟通处理
        </el-row>
      </div>
      <div v-else>
        <el-steps :active="active" finish-status="success">
          <el-step title="申请中"></el-step>
          <el-step title="待处理"></el-step>
          <el-step title="退货中"></el-step>
          <el-step title="已完成"></el-step>
        </el-steps>
        <!--    处理中    -->
        <div style="text-align: left">
          <el-form :model="reasonForm" :rules="rules" ref="reasonForm" label-width="120px">
            <el-form-item label="选择原因" prop="reason">
              <el-select v-model="reasonForm.reason" placeholder="请选择">
                <el-option
                    :disabled="disabled"
                    v-for="item in reasonList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="填写说明" prop="description">
              <el-input v-model="reasonForm.description" :disabled="disabled" type="textarea"
                        placeholder="请填写说明"></el-input>
            </el-form-item>
            <el-form-item label="上传凭证">
              <el-upload
                  class="upload-demo"
                  :action="uploadPath"
                  :headers="headers"
                  name="multipartFile"
                  :limit="3"
                  :on-success="handleSuccess"
                  :on-remove="handleRemove"
                  :file-list="fileList"
                  list-type="picture"
              >
                <el-button type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>


            <el-form-item label="所在地区:">
              <el-cascader
                  :disabled="active==0"
                  v-model="district" separator="-" :options="options" :props="optionProps"
                           style="width: 350px;" @change="handleChange"/>
            </el-form-item>


            <el-form-item label="回收人名称" prop="takeName">
              <el-input v-model="reasonForm.takeName"
                        :disabled="active==0"
                        placeholder="请填写回收人名称"></el-input>
            </el-form-item>

            <el-form-item label="回收人电话" prop="takePhone">
              <el-input v-model="reasonForm.takePhone"
                        :disabled="active==0"
                        placeholder="请填写回收人电话"></el-input>
            </el-form-item>

            <el-form-item label="回收人邮编" prop="takePostCode">
              <el-input v-model="reasonForm.takePostCode"
                        :disabled="active==0"
                        placeholder="请填写回收人邮编"></el-input>
            </el-form-item>

            <el-form-item label="详细地址" prop="takeDetailAddress">
              <el-input v-model="reasonForm.takeDetailAddress"
                        :disabled="active==0"
                        type="textarea" placeholder="请填写详细地址"></el-input>
            </el-form-item>

            <el-form-item label="处理结果备注" prop="handleNote" v-if="active==2">
              <el-input v-model="reasonForm.handleNote"
                        :disabled="active!=0"
                        type="textarea" placeholder="请填写详细地址"></el-input>
            </el-form-item>

            <el-form-item>
              注意：请联系商家，提供回收地址,<span style="color: red">申请通过后请正确填写回收地址,否则解决退货</span>，退货完成后，系统会自动退款。
            </el-form-item>
          </el-form>
        </div>

      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showReturn = false">取 消</el-button>
        <el-button type="primary" v-if="active===0 || active===1" @click="submitForm('reasonForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  Card,
  Row,
  Col,
  Divider,
  Table,
  TableColumn,
  Image,
  Steps,
  Step,
  Form,
  FormItem,
  Select,
  Option,
  Input,
  Upload,
  Button,
  Dialog,
  Message
} from 'element-ui';
import base64 from "@/utils/base64";
import {
  addOrderReturnApply,
  getOrderReturnApplyList,
  getOrderReturnReasonList,
  updateOrderReturnApply,
  updateStatus
} from "@/api/order/order";

export default {
  name: 'OrderList',
  components: {
    'el-card': Card,
    'el-row': Row,
    'el-col': Col,
    'el-divider': Divider,
    'el-table': Table,
    'el-table-column': TableColumn,
    'el-image': Image,
    'el-steps': Steps,
    'el-step': Step,
    'el-form': Form,
    'el-form-item': FormItem,
    'el-select': Select,
    'el-option': Option,
    'el-input': Input,
    'el-upload': Upload,
    'el-button': Button,
    'el-dialog': Dialog
  },
  props: {
    data: Array
  },
  data() {
    // 验证规则
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入回收人电话'));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入有效的手机号码'));
      } else {
        callback();
      }
    };
    const validatePostCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入回收人邮编'));
      } else if (!/^\d{6}$/.test(value)) {
        callback(new Error('邮编格式不正确'));
      } else {
        callback();
      }
    };
    return {
      disabled: false,
      timeOut: 1000,
      showReturn: false,
      active: 0,
      productRow: {},
      orderDetail: {},
      reasonList: [],
      reasonForm: {
        reason: '',
        address: '',
        description: ''
      },
      fileList: [],
      uploadPath: process.env.VUE_APP_BASE_API + "/oss/upload",
      headers: {
        Authorization: localStorage.getItem("TOKEN"),
      },
      rules: {
        reason: [
          { required: true, message: '请选择退货原因', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请填写退货说明', trigger: 'blur' },
          { min: 10, message: '退货说明至少需要10个字符', trigger: 'blur' }
        ],
        // takeName: [
        //   { required: true, message: '请填写回收人名称', trigger: 'blur' }
        // ],
        // takePhone: [
        //   { required: true, validator: validatePhone, trigger: 'blur' }
        // ],
        // takePostCode: [
        //   { required: true, validator: validatePostCode, trigger: 'blur' }
        // ],
        // takeDetailAddress: [
        //   { required: true, message: '请填写详细地址', trigger: 'blur' }
        // ]
      },
      district: [],
      options: [],
      optionProps: {
        value: "name",
        label: "name",
        children: "children",
      },
      area:""
    };
  },
  methods: {
    filterOptions(options) {
      return options.filter(option => {
        if (option.children) {
          // 递归处理子级
          option.children = this.filterOptions(option.children);
          // 如果处理后的子级为空，则直接删除children属性
          if (option.children.length === 0) {
            delete option.children;
          }
        }
        // 保留有子级或本身没有子级的节点
        return !option.children || option.children.length > 0;
      });
    },
    getAddress() {
      this.$api.common.getAddress().then((res) => {
        if (res.code == 200) {
          this.options = this.filterOptions(res.data)
        }
      });
    },
    handleChange(arr) {
      this.area = `${arr[0]}-${arr[1]}-${arr[2]}`;
    },
    getOrderReturnApplyList() {
      this.$api.order.getOrderReturnApplyList(this.orderDetail.id, this.productRow.productId).then(res => {
        if (res.code == 200) {
          this.reasonForm = {
            reason: '',
            address: '',
            description: ''
          }
          if (res.data != null) {
            this.reasonForm = res.data
            this.active = res.data.status
            // console.log(this.active)
            res.data.productPic.split(",").forEach(item=>{
              this.fileList.push({
                name: item,
                url: item,
              });
            })
            //回显地址填写地址
              this.district = [
                res.data.takeProvince,
                res.data.takeCity,
                res.data.takeRegion || '' // 如果 region 不存在，设置为空字符串
              ].filter(item => item !== ''); // 过滤掉空字符串
            console.log(this.disabled)
            if (res.data.status !=0){
              this.disabled = true
            }
          }
        }
      })
    },
    handleSuccess(res, file) {
      this.fileList.push({
        name: file.data,
        url: res.data,
      });
    },
    handleRemove(file) {
      this.fileList.splice(0, 1);
    },
    //退货申请
    handleOrderReturn(order, row) {
      this.showReturn = true
      this.productRow = row
      this.orderDetail = order
      this.getOrderReturnReasonList()
      this.getOrderReturnApplyList()
      this.getAddress()
    },
    getOrderReturnReasonList() {
      this.$api.order.getOrderReturnReasonList().then(res => {
        if (res.code == 200) {
          this.reasonList = res.data
        }
      })
    },
    btnStatus(status) {
      const statusMap = {
        0: '付款',
        1: '催发货',
        2: '确认收货',
        3: '评价',
        4: '删除'
      };
      return statusMap[status] || '未知操作';
    },
    handleOrderAction(order) {
      if (order.status == 0) {
        this.$router.push({
          path: "/payPrice",
          query: {
            orderId: base64.encode(JSON.stringify({'orderSn': order.orderSn}))
          }
        })
      } else if (order.status == 1) {
        this.$message.success("已通知客服~")
      } else if (order.status == 2) {
        this.$api.order.updateStatus(order.id, (order.status + 1)).then(res => {
          if (res.code == 200) {
            this.$emit('getOrderList', order.status)
          }
        })
      } else if (order.status == 3) {
        // 这里可以添加评价逻辑
      } else if (order.status == 4) {
        this.$confirm('确定删除该订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.order.deleteOrder(order.id).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功~")
              this.$emit('getOrderList', order.status)
            }
          })
        })
      }
    },
    getOrderStatus(status) {
      const statusMap = {
        0: '待付款',
        1: '已付款',
        2: '待收货',
        3: '已完成',
        4: '已关闭',
        5: '已失效'
      };
      return statusMap[status] || '未知状态';
    },
    setAddress(order) {
      return `${order.receiverProvince}${order.receiverCity}${order.receiverRegion}${order.receiverDetailAddress}`;
    },
    getProductAttr(attrString) {
      try {
        const attrs = JSON.parse(attrString);
        return attrs.map(attr => `${attr.key}: ${attr.value}`).join(', ');
      } catch (e) {
        return '未知规格';
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.reasonForm.id) {//开始申请
            let data = this.reasonForm
            data.orderId = this.orderDetail.id
            data.productId = this.productRow.productId
            data.orderSn = this.orderDetail.orderSn
            data.productAttr = this.productRow.productAttr
            data.productBrand = this.productRow.productBrand
            data.productCount = this.productRow.productQuantity
            data.productName = this.productRow.productName
            data.productPic = this.productRow.productPic
            data.productPrice = this.productRow.productPrice
            data.productSn = this.productRow.productSn
            data.productRealPrice = this.productRow.realAmount

            this.$api.order.addOrderReturnApply(data).then(res => {
              if (res.code == 200) {
                this.showReturn = false;
                Message.success("申请退货成功~")
              }
            })
          }else{
            this.reasonForm.takeProvince=this.district[0]
            this.reasonForm.takeCity=this.district[1]
            this.reasonForm.takeRegion=this.district[2] || ""
            this.reasonForm.productPic = this.fileList.map(item => item.url).join(',')
            this.$api.order.updateOrderReturnApply(this.reasonForm).then(res=>{
              if (res.code == 200) {
                this.showReturn = false;
                Message.success("修改退货申请成功~")
              }
            })
          }

        } else {
          Message.error("请检查输入项");
          return false;
        }
      });
    },
    resetForm() {
      // this.$refs['reasonForm'].resetFields();
      this.fileList = [];
    }
  }
};
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.float-right {
  float: right;
}

.el-card {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
}
</style>
